# -*- coding: utf-8 -*-

'''eof
name:最近3M活跃品类数量
code:Mon3ActiveCnt
tableName:
columnName:
groups:烟商
dependencies:BTM
type:常用指标
datasourceType:在线指标
description:
eof'''

'''
最近90天内订货量大于等于9条的种类个数
'''

import sys
import pandas as pd
import datetime
import re

reload(sys)
sys.setdefaultencoding('utf-8')


def Mon3ActiveCnt():
    null_type_list = ['', None, 'null', 'Null', '/', ' ']
    active_count = {}
    count = []
    try:
        BTM_ = BTM['data']
        if Formate(BTM_.get('bbd_dotime')) is not None:
            ApplTime = datetime.datetime.strptime(Formate(BTM_['bbd_dotime']), '%Y%m%d')
            last_year_days_list = [(ApplTime - pd.tseries.offsets.DateOffset(days=i)).strftime('%Y%m%d') \
                                   for i in [90, 0]]
        else:
            last_year_days_list = [(datetime.datetime.now() - pd.tseries.offsets.DateOffset(days=i)).strftime('%Y%m%d') \
                                   for i in [90, 0]]
    except:
        return u'缺失值'

    try:
        if BTM_.has_key('indent') and BTM_['indent'] not in null_type_list \
            and len(BTM_['indent']) >= 1:
            for i in BTM_['indent']:
                if i.has_key('indentDate') and i['indentDate'] not in null_type_list \
                    and i.has_key('indentDetails') and i['indentDetails'] not in null_type_list \
                    and Formate(i['indentDate']) is not None \
                    and Formate(i['indentDate']) > last_year_days_list[0] \
                    and Formate(i['indentDate']) <= last_year_days_list[1] \
                    and len(i['indentDetails']) >= 1:
                    for j in i['indentDetails'] :
                        if j.has_key('orderQuantity') and j['orderQuantity'] not in null_type_list \
                            and isfloat(j['orderQuantity']) \
                            and j.has_key('tradeName') and j['tradeName'] not in null_type_list:
                            if active_count.has_key(j['tradeName']):
                                key = j['tradeName']
                                active_count[key].append(float(j['orderQuantity']))
                            else:
                                active_count.update({j['tradeName']:[float(j['orderQuantity'])]})

            for k in active_count.keys():
                count.append(sum(active_count[k]))
            if count != []:
                return round(float(len([i for i in count if i >=9])), 4)
            else:
                return u'缺失值'
        else:
            return u'缺失值'
    except:
        return u'缺失值'

def isfloat(x):
    try:
        if isinstance(float(x), float) and float(x)>=0:
            return True
        else:
            return False
    except:
        return False

#统一时间格式为'20180528'-> '%Y%m%d'
def Formate(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    date = None
    return date


result = Mon3ActiveCnt()